package com.micro.ai.models.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.models.entity.ModelVersion;
import com.micro.ai.models.service.ModelVersionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 模型版本控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/model-versions")
@Tag(name = "模型版本管理", description = "模型版本的增删改查、当前版本管理")
public class ModelVersionController {

    @Autowired
    private ModelVersionService modelVersionService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:version:create')")
    @Operation(summary = "创建模型版本", description = "创建新的模型版本")
    public ApiResponse<ModelVersion> create(@Valid @RequestBody ModelVersion version) {
        log.info("创建模型版本请求: modelId={}, versionName={}", 
                version.getModelId(), version.getVersionName());
        ModelVersion result = modelVersionService.create(version);
        return ApiResponse.success("创建成功", result);
    }

    @GetMapping("/by-model/{modelId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:version:view')")
    @Operation(summary = "获取模型的所有版本", description = "根据模型ID获取该模型的所有版本列表")
    public ApiResponse<Page<ModelVersion>> listByModelId(
            @Parameter(description = "模型ID", required = true) @PathVariable String modelId) {
        log.info("查询模型版本列表: modelId={}", modelId);
        
        Page<ModelVersion> page = modelVersionService.listByModelId(modelId);
        return ApiResponse.success(page);
    }

    @PatchMapping("/{id}/set-current")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:version:update')")
    @Operation(summary = "设置当前版本", description = "将指定版本设为模型的当前版本")
    public ApiResponse<Void> setCurrent(
            @Parameter(description = "版本ID", required = true) @PathVariable String id) {
        log.info("设置当前版本请求: versionId={}", id);
        
        modelVersionService.setCurrent(id);
        return ApiResponse.successVoid("设置当前版本成功");
    }

}

